package com.zkzx.company.base.service;


import com.zkzx.common.constants.SourceEnum;
import com.zkzx.common.global.Global;
import com.zkzx.common.truck.command.TruckCommand;
import com.zkzx.common.truck.constants.TruckStatusEnum;
import com.zkzx.common.truck.constants.VehicleEnum;
import com.zkzx.common.truck.model.CompanyTruckVO;
import com.zkzx.common.truck.model.TruckListVO;
import com.zkzx.common.truck.param.TruckFilterParam;
import com.zkzx.common.truck.vo.HeaderLicenseVO;
import com.zkzx.common.truck.vo.TruckSourceVO;
import com.zkzx.common.truck.vo.TruckStatisticsVO;
import com.zkzx.common.truck.vo.TypeVO;
import com.zkzx.common.vo.PageResult;
import com.zkzx.common.vo.RequestFilterParams;
import com.zkzx.common.vo.StatusVO;
import com.zkzx.company.base.mapper.CompanyTruckMapper;
import com.zkzx.company.base.mapper.entity.CompanyTruck;
import com.zkzx.company.base.mapper.entity.CompanyTruckExample;
import com.zkzx.util.data.CutStringUtil;
import com.zkzx.util.sql.SQLUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 北京中科智兴物联科技有限公司 @版权所有
 *
 * @Author: zhaoyihe@zkraising.com
 * @Date: 2021/05/11/20:23
 * @Description:
 */
@Slf4j
@Service
public class CompanyTruckService {

    @Resource
    private CompanyTruckMapper companyTruckMapper;

    /**
     * 根据车id或者企业id查询中间表信息
     * @param truckId 车辆id
     * @param companyId 企业id
     * @return 证件信息
     */
    public List<CompanyTruckVO> getByTruckIdAndCompanyId(Integer truckId,Integer companyId){
        CompanyTruckExample companyTruckExample = new CompanyTruckExample();

        CompanyTruckExample.Criteria criteria = companyTruckExample.createCriteria();

        if(Objects.nonNull(truckId) && truckId > Global.ZERO){
            criteria.andTruckidEqualTo(truckId);
        }

        if(Objects.nonNull(companyId) && companyId > Global.ZERO ){
            criteria.andCompanyidEqualTo(companyId);
        }

        List<CompanyTruck> list =  companyTruckMapper.selectByExample(companyTruckExample);


        if (CollectionUtils.isEmpty(list)){
            return Collections.emptyList() ;
        }

        return list.stream().map(companyTruck ->
                   CompanyTruckVO.builder()
                   .id(companyTruck.getId())
                   .companyId(companyTruck.getCompanyid())
                   .truckId(companyTruck.getTruckid())
                   .headerLicense(companyTruck.getHeaderlicense())
                   .type(companyTruck.getType())
                   .status(companyTruck.getStatus())
                   .source(companyTruck.getSource()).build()
                ).collect(Collectors.toList());

    }


    /**
     * 车辆关联企业信息
     * @param command 关联入参
     * @param companyId 企业id
     */
    public void addOrUpdate(TruckCommand command, int companyId) {
        CompanyTruck companyTruck = new CompanyTruck();
        companyTruck.setTruckid(command.getId());
        companyTruck.setHeaderlicense(Optional.ofNullable(command.getHeaderLicenseVO()).map(HeaderLicenseVO::getLicence).orElse(null));
        companyTruck.setType(command.getType());
        companyTruck.setStatus(command.getStatus());
        companyTruck.setSource(command.getSource());
        companyTruck.setLastmodifiedtime(new Date());
        CompanyTruckExample companyTruckExample = new CompanyTruckExample();

        // 当是企业修改 全量更新所有的关系表中的信息
        if(companyId == Global.ZERO){
            companyTruckExample.createCriteria().andTruckidEqualTo(command.getId());
            companyTruckMapper.updateByExampleSelective(companyTruck,companyTruckExample);
            return;
        }

        companyTruck.setCompanyid(companyId);
        companyTruckExample.createCriteria().andTruckidEqualTo(command.getId()).andCompanyidEqualTo(companyId);
        List<CompanyTruck> companyTrucks = companyTruckMapper.selectByExample(companyTruckExample);
        Optional<CompanyTruck> first = companyTrucks.stream().findFirst();
        if(first.isPresent()){
            CompanyTruck truck = first.get();
            companyTruck.setId(truck.getId());
            companyTruckMapper.updateByPrimaryKeySelective(companyTruck);
            return;
        }
        companyTruckMapper.insert(companyTruck);
    }


    /**
     *  分页车辆列表
     * @param filterParam 查询条件
     * @param params 分页参数
     * @param companyId 企业id
     * @return 分页车辆列表
     */
    public PageResult<TruckListVO> find(TruckFilterParam filterParam, RequestFilterParams params, Integer companyId) {

        CompanyTruckExample companyTruckExample = buildCompanyTruckExample(filterParam, companyId);

        long totalNum = companyTruckMapper.countByExample(companyTruckExample);
        if (totalNum <= Global.ZERO){
            return new PageResult<>(params.getPage(),params.getPerPage(), Collections.emptyList(), Global.ZERO);
        }


        companyTruckExample.setOrderByClause(params.getField().concat(" ").concat(params.getOrder()));
        companyTruckExample.page(params.getPage() - Global.ONE , params.getPerPage());

        List<CompanyTruck> companyTrucks = companyTruckMapper.selectByExample(companyTruckExample);

        List<TruckListVO> list=companyTrucks.stream().map(truck -> TruckListVO.builder()
                .id(truck.getTruckid())
                .companyId(truck.getCompanyid())
                .typeVO(buildTypeVO(truck.getType()))
                .truckSourceVO(buildTruckSourceVO(truck.getSource()))
                .status(StatusVO.builder()
                        .value(TruckStatusEnum.valueOf(truck.getStatus()).name())
                        .description(TruckStatusEnum.valueOf(truck.getStatus()).getDescription())
                        .build())
                .headerLicenseVO(HeaderLicenseVO.builder()
                        .province(CutStringUtil.getFirst(truck.getHeaderlicense()))
                        .number(CutStringUtil.getSix(truck.getHeaderlicense()))
                        .licence(truck.getHeaderlicense())
                        .build())
                .build()).collect(Collectors.toList());

        return new PageResult<>(params.getPage(),params.getPerPage(),list, (int) totalNum);
    }

    /**
     * 封装车辆来源
     * @param source 车辆来源
     * @return 车辆来源
     */
    private TruckSourceVO buildTruckSourceVO(String source){
        if(StringUtils.isEmpty(source)){
            return null;
        }
        return TruckSourceVO.builder()
                .name(SourceEnum.valueOf(source).name())
                .value(SourceEnum.valueOf(source).getDescription())
                .build();
    }

    /**
     * 封装车辆类型
     * @param type 车辆类型
     * @return 车辆类型
     */
    private TypeVO buildTypeVO(String type){
        if(StringUtils.isEmpty(type)){
            return null;
        }
        return TypeVO.builder()
                .name(VehicleEnum.valueOf(type).name())
                .value(VehicleEnum.valueOf(type).getValue())
                .build();
    }



    /**
     * 封装车辆查询条件
     * @param filterParam 查询条件
     * @param companyId 企业id
     * @return 查询条件
     */
    private CompanyTruckExample buildCompanyTruckExample(TruckFilterParam filterParam, Integer companyId){
        CompanyTruckExample companyTruckExample = new CompanyTruckExample();

        CompanyTruckExample.Criteria criteria = companyTruckExample.createCriteria();
        if (Global.ZERO < companyId){
            criteria.andCompanyidEqualTo(companyId);
        }

        if(!StringUtils.isEmpty(filterParam.getHeaderLicense())){
            criteria.andHeaderlicenseLike(SQLUtil.valueBuildLike(filterParam.getHeaderLicense()));
        }

        if(!StringUtils.isEmpty(filterParam.getSource())){
            criteria.andSourceEqualTo(filterParam.getSource());
        }
        if(!StringUtils.isEmpty(filterParam.getStatus())){
            criteria.andStatusEqualTo(filterParam.getStatus());
        }
        if(!StringUtils.isEmpty(filterParam.getType())){
            criteria.andTypeEqualTo(filterParam.getType());
        }
        if(CollectionUtils.isNotEmpty(filterParam.getStatusList())){
            criteria.andStatusIn(filterParam.getStatusList());
        }
        return companyTruckExample;
    }

    /**
     * 查询可用车辆信息
     * @param companyId 企业id
     * @return TruckStatisticsVO
     */
    public TruckStatisticsVO getTruckStatistics(Integer companyId){

        int runNum = getTruckRunNum(companyId);
        int sucNum = getTruckSucNum(companyId);

        return TruckStatisticsVO.builder()
                .usableTruck(sucNum)
                .runTruck(runNum)
                .build();

    }


    public int getTruckSucNum(Integer companyId){

        CompanyTruckExample companyTruckExample = new CompanyTruckExample();
        CompanyTruckExample.Criteria criteria = companyTruckExample.createCriteria();
        criteria.andCompanyidEqualTo(companyId);
        criteria.andStatusEqualTo(TruckStatusEnum.VERIFY_SUCCESS.name());

        long sucNum = companyTruckMapper.countByExample(companyTruckExample);

        return (int)sucNum;
    }



    public int getTruckRunNum(Integer companyId){

        CompanyTruckExample runCompanyTruckExample = new CompanyTruckExample();
        CompanyTruckExample.Criteria runCriteria = runCompanyTruckExample.createCriteria();
        runCriteria.andCompanyidEqualTo(companyId);
        List<String> list = new ArrayList<>();
        list.add(TruckStatusEnum.APPROVE_FAIL.name());
        list.add(TruckStatusEnum.APPROVE_ING.name());
        list.add(TruckStatusEnum.NO_SUBMIT.name());
        runCriteria.andStatusIn(list);

        long runNum = companyTruckMapper.countByExample(runCompanyTruckExample);

        return (int)runNum;
    }
}
